<template>
  <div ref="gaugeCharts" :style="{ 'width': width, 'height': height }"></div>
</template>

<script>
import * as echarts from 'echarts';
import macarons from './macarons.json';
import { on, off } from "@/utils";

export default {
  name: 'PieChart',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    height: {
      type: String,
      default: '480px'
    },
    width: {
      type: String,
      default: '100%'
    },
    chartData: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      gaugeCharts: null
    };
  },
  methods: {
    initChart() {
      this.gaugeCharts = echarts.init(this.$refs.gaugeCharts, 'macarons');
      this.setOption(this.chartData);
    },
    setOption({unit, max, splitNumber, data} = {}) {
      const option = {
        series: [{
          type: 'gauge',
          startAngle: 215,
          endAngle: -35,
          splitNumber: splitNumber,
          radius: '85%',
          axisLine: {
            lineStyle: {
              width: 30,
              color: [
                [0.3, '#67e0e3'],
                [0.7, '#37a2da'],
                [1, '#fd666d']
              ]
            }
          },
          pointer: {
            itemStyle: {
              color: 'auto'
            }
          },
          axisTick: {
            distance: -30,
            length: 8,
            lineStyle: {
              color: '#fff',
              width: 2
            }
          },
          splitLine: {
            distance: -30,
            length: 30,
            lineStyle: {
              color: '#fff',
              width: 4
            }
          },
          axisLabel: {
            color: 'auto',
            distance: 40,
            fontSize: 20
          },
          detail: {
            valueAnimation: true,
            formatter: `{value} ${unit}`,
            color: 'auto'
          },
          min: 0,
          max: max,
          data: data
        }]
      };
      this.gaugeCharts.setOption(option);
    },
    resize() {
      this.gaugeCharts.resize();
    },
    showLoading() {
      this.gaugeCharts && this.gaugeCharts.showLoading();
    },
    hideLoading() {
      this.gaugeCharts && this.gaugeCharts.hideLoading();
    }
  },
  watch: {
    chartData: {
      handler(val) {
        this.gaugeCharts.clear();
        this.setOption(val);
      },
      deep: true
    },
    loading(val) {
      if (val) {
        this.showLoading();
      } else {
        this.hideLoading();
      }
    }
  },
  mounted() {
    echarts.registerTheme('macarons', macarons.theme);
    this.$nextTick(() => {
      this.initChart();
      on(window, 'resize', this.resize);
    });
  },
  beforeDestroy() {
    off(window, 'resize', this.resize);
    if (!this.gaugeCharts) {
      return;
    }
    this.gaugeCharts.dispose();
    this.gaugeCharts = null;
  },
};
</script>

<style scoped>

</style>
